package com.liuyi.framework.web.encrypt;
import cn.hutool.core.util.StrUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * <p>
 * 解密转换类
 * </p>
 *
 * @author Mr.Fmy
 * @since 2021-02-01
 */
public class DecryptHttpInputMessage implements HttpInputMessage {

    private HttpInputMessage inputMessage;
    private String charset;
    private String keyStr;

    public DecryptHttpInputMessage(HttpInputMessage inputMessage, String charset, String keyStr) {
        this.inputMessage = inputMessage;
        this.charset = charset;
        this.keyStr = keyStr;
    }

    @Override
    public InputStream getBody() throws IOException {
        if (StrUtil.isBlank(keyStr)){
            return inputMessage.getBody();
        }
        return new ByteArrayInputStream(EncryptionTool.decrypt(keyStr, inputMessage.getBody(), charset));
    }

    @Override
    public HttpHeaders getHeaders() {
        return inputMessage.getHeaders();
    }
}
